//
//  SearchVC.m
//  DataStatistics
//
//  Created by Kang on 15/10/13.
//  Copyright © 2015年 YTYangK. All rights reserved.
//


#import "SearchVC.h"
#import "EquipmenCell.h"
#import "CoverView.h"

//#import "EquipmenCellViewModel.h" // 设备列表ViewModel
#import "SearchCityViewModel.h" // 搜索ViewModel
#import "SearchViewModel.h" //搜索ViewModel
// data
#import <CoreData/CoreData.h>

#import "EquipmenDetailsViewModel.h" // 设备详情ViewModel
#import "SystemInfoController.h"// 扫描获取到的设备详情

#import "UIView+RGSize.h"
#import "AppDelegate.h"
#import "CtrlCodeScan.h" //扫描
#import "DevicesWelcome.h"


#define  RECORD_INDEX_PATH   @"recordIndexPath"

@interface SearchVC () <UIPopoverPresentationControllerDelegate, CtrlCodeScanDelegate, EquipmenCellDelegate,SystemInfoControllerDelegate,SearchHeadViewDelegate,SearchRegionChoiceDelegate,NSObject> {

    CGFloat _popoverWidth;
    CGFloat _popoverHeight;
    CGFloat _ckBtnY;
    CGFloat _tabBartHeight;

    // 需要其他控件控制刷新
    MJRefreshNormalHeader* header;
    MJRefreshBackNormalFooter* footer;

    // 请求字典
    NSDictionary* parameterDic;
    // 判断是否点击了
    BOOL isDetermineClick;
    //保存数 历史数量
    NSString * recordChoiceDevice;
    // 判断方法是否添加选择的地区参数
    BOOL isChdoneButClick;
   // 判断是否点击显示地区按钮, YES -显示，NO -隐藏
    BOOL areaButClick;
    
    NSString *countries;
    NSString *state;
    UIView *keyboardvView;
    CoverView *cover;
    NSString *key;
    
}


@property (strong, nonatomic) IBOutlet SearchHeadView* sondView;

/** 透明覆盖背景 */
@property (strong, nonatomic) UIView* maskView;
/** 地区关闭 -按钮*/
@property (strong, nonatomic) UIButton* ckBtn;

/**
 *  接收本地语言标识
 */
@property (strong, nonatomic) NSString *localStr;
/** 没显示数据时的图片 */
@property (strong, nonatomic) UIButton *notDataBtn;
@property (assign, nonatomic) BOOL  isLoadDataBtn;
@property (nonatomic)float pickView_H;


@end

@implementation SearchVC

singleton_for_implementation(SearchVC)

- (void)viewDidLoad {
    [super viewDidLoad];
  
//    [self welcome];
    
    // 定时器
//   NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
//    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupUnreadCount) name:@"setBadge" object:nil]; // 激活时，推送时

    [[UIApplication sharedApplication] addObserver:self forKeyPath:@"applicationIconBadgeNumber" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"监控属性值变化"];
    

    [self updateUI];
    [self setupMiddleNavigationItem];
    
    [self tableViewWithModel];
    self.searchTableView.separatorStyle = UITableViewCellAccessoryNone;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}





-(void)welcome
{
    cover = [[CoverView alloc]init];
    
    [cover setCoverObjectForKey:key = @"DevicesView"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapView)];
    
    [cover.DevicesView addGestureRecognizer:tap];
    
}


-(void)TapView
{
    [cover.DevicesView removeFromSuperview];
    
    [[NSUserDefaults standardUserDefaults]setObject:@"YES" forKey:key];

}


#define mark - Other
/**
 * 监控数值变化
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    NSInteger integer  = [UIApplication sharedApplication].applicationIconBadgeNumber;
    NSLog(@"----->%ld",(long)integer);
    if ([keyPath isEqualToString:@"applicationIconBadgeNumber"]) {
        if (integer <=0) {
            self.navigationController.tabBarItem.badgeValue = nil;
        }else {
            self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",(long)integer];
        }
    }
    NSLog(@"%@---->%@---->%@--->%@",keyPath,object,change,context);
}
/**
 *  设置更新的内容
 */
- (void)setupUnreadCount {
    NSString *str = [SearchViewModel sharedSearchViewModel].unreadCount;
    if (str.intValue<= 0 ) {
         [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    }
    
    [header beginRefreshing]; // 刷新列表
}

/**
 *  清除未读信息 - 计数
 *
 *  @param count 需要减少的数量 - int
 */
- (void)subtractUnreadCount:(int)count {
     int resultCount = 0;
    NSString* status =  [NSString stringWithFormat:@"%ld", (long)[UIApplication sharedApplication].applicationIconBadgeNumber]; // 获取推送总数
    NSString *ecvm_unreadCount = [SearchViewModel sharedSearchViewModel].unreadCount; // 后台总数
    
    // 被减数 是否为 0 或者小于零
    if (count > 0) {
       
     // 判断tab 有数量不
        if ([self.navigationController.tabBarItem.badgeValue intValue] >= 0) {
            if (ecvm_unreadCount.intValue >= 0) {
                 resultCount = status.intValue - count;
            }else {
            resultCount = 0;
            }
        }
        else {
             resultCount = 0;
        }
        
        // 判断计算的变量 coun 值
        if (resultCount <= 0) {
            self.navigationController.tabBarItem.badgeValue = nil;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        }
        else {
            self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", resultCount];
            [UIApplication sharedApplication].applicationIconBadgeNumber = resultCount;
        }
        [SearchViewModel sharedSearchViewModel].unreadCount = [NSString stringWithFormat:@"%d", resultCount];
       // [[NSNotificationCenter defaultCenter] postNotificationName:UITableViewSelectionDidChangeNotification object:self];
    }
    else {
        
        if (ecvm_unreadCount.intValue > 0) {
            [UIApplication sharedApplication].applicationIconBadgeNumber = ecvm_unreadCount.integerValue;
        }else {
          //  小于等于0
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        }
    }

}
// 前台通知来时计算未读信息
- (void)addUnreadCount:(id)vlue {
    
    NSDictionary  *dic = [vlue  objectForKey:@"aps"];
    NSString *deviceCodeStr = [vlue  objectForKey:@"deviceCode"];
    
    int inde = 0;
    for (EListModel* obj in _searchModelAry) {
        NSLog(@"%d - - ->%@",inde,obj.deviceCode);
        if ([deviceCodeStr isEqualToString:obj.deviceCode]) {
            
            
            EListModel* list = _searchModelAry[inde];
#warning 百度后台推送的统一都为 0
            //            NSString* status =  [NSString stringWithFormat:@"%ld", (long)[UIApplication sharedApplication].applicationIconBadgeNumber]; // 获取推送总数
            NSString *status = [dic objectForKey:@"badge"];
            
            NSString *unr     = [SearchViewModel sharedSearchViewModel].unreadCount;//[EquipmenCellViewModel getEquipmenVM].unreadCount; //后台总数
            int i = 0;
            if (status.intValue >= unr.intValue) { //正常来说推送数 大于后台获取到的保留数量
                i  = (status.intValue  - unr.intValue) <= 0 ?  0: (status.intValue - unr.intValue)+ list.unreadCount;
                NSLog(@"---->%d",i);
            }else  {
                i =  (unr.intValue - status.intValue) <=  0  ? 0 : (unr.intValue - status.intValue)+ list.unreadCount;   //(unr.intValue - status.intValue)
            }
            
            
            [SearchViewModel sharedSearchViewModel].unreadCount = status;
            [list setValue:[NSNumber numberWithInt:i] forKey:@"unreadCount"];
            
            NSIndexPath *indexPat =  [NSIndexPath indexPathForRow:inde inSection:0];
            [self.searchTableView reloadRowsAtIndexPaths:@[ indexPat ] withRowAnimation:UITableViewRowAnimationNone];
            break;
        }
        inde++;
    }
    
}

- (void)JumpWithVlue:(id)vlue {
    NSDictionary  *dic = vlue;
    NSLog(@"%@",dic);
    
    int inde = 0;
    for (EListModel* obj in _searchModelAry) {
        NSLog(@"%d - - ->%@",inde,obj.deviceCode);
        if ([[vlue objectForKey:@"deviceCode"] isEqualToString:obj.deviceCode]) {
          
            //EquipmenCellViewModel* cellViewmodel = [[EquipmenCellViewModel alloc] init];
            EListModel* list = _searchModelAry[inde];
            recordChoiceDevice = list.deviceCode;   // 后台- 单条数
            [self subtractUnreadCount:list.unreadCount];
            [list setValue:@0 forKey:@"unreadCount"];
       
            NSIndexPath *indexPat =  [NSIndexPath indexPathForRow:inde inSection:0];
            [self.searchTableView reloadRowsAtIndexPaths:@[ indexPat ] withRowAnimation:UITableViewRowAnimationNone];
            [SearchViewModel jumpListDetailWithListModel:_searchModelAry[inde] forViewController:self];
    
            break;
        }
        inde++;
    }

}




#pragma mark - Table view UI and Data

- (void)updateUI {
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_WIDTH, @"320.0")) {
            self.sondView.height -= 15;
        }else {}
    
    _isSearchJumpLiet     =   NO;
    _isLoadDataBtn          =   NO;
     isDetermineClick       =   NO;      //状态标识 -是否点击了某行？
    _isToSearchUpdate     = YES;         
    self.clickFinished        = YES;
    isChdoneButClick      = NO;
    areaButClick              = NO;
    
    self.sondView.searchHeadDelegate = self;
    self.pickerView.delegate = self;
    
    // 搜索
    self.page = 1;
    self.searchTableView.separatorStyle = UITableViewCellSeparatorStyleNone; //清除下划线
    self.searchTableView.backgroundColor = [UIColor blackColor];
    self.sondView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.sondView.frame.size.height);
    self.pickerView.cityTableView.separatorColor =  RGB(66, 66, 66, 1);
    [self.pickerView.cityTableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 18)];
    self.pickerView.cityTableView .backgroundColor = RGB(38, 39, 39, 1);
}

- (void)tableViewWithModel {
    
    header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isToSearchUpdate = YES;
        self.page = 1;
        [self requestURLwithViewForpage:self.page];
    }];
    
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.searchTableView.header = header;
    [self.sondView isRedDotSort:YES];
    [header beginRefreshing];
    
    footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.isToSearchUpdate = NO;
        self.page++;
        [self requestURLwithViewForpage:self.page];
        
    }];
    self.searchTableView.footer = footer;
}

- (void)requestURLwithViewForpage:(int)page {
    NSNumber* num = [NSNumber numberWithInt:page];
    NSString *searStr =   isChdoneButClick ?  [UtilToolsClss addingPercentEscapesUsingEncodingWithurlStr:self.pickerView.SRCView_searchValueStr] : @"" ;
    
    if (self.sondView.redDotSort) { // 是否使用红点排序
        [self.sondView resetSearchHeadWithView:self.view];
    }
    NSNumber* scr = [NSNumber numberWithInt:self.sondView.screeningState];
    
    
 
        parameterDic = @{ @"current_page" : num,
                          @"mapVo[deviceCode]" : [UtilToolsClss addingPercentEscapesUsingEncodingWithurlStr:self.searchTextField.text],
                          @"ascendingOrder" : scr,
                          @"orderName" : self.sondView.sortMethodStr,
                          @"areaName" : searStr,
                          @"local" : [self localStr]};
    
    NSLog(@"请求字典 =====  %@",parameterDic);

    [SearchViewModel requestWithUrlForSearchIn:self andParam:parameterDic success:^(EquipmenModel *model) {
        [SearchViewModel sharedSearchViewModel].unreadCount = model.unreadAllCount;
        [self.searchTableView.header endRefreshing];
        [self.searchTableView.footer endRefreshing];
        self.sondView.SHView_timeView.userInteractionEnabled = YES;
        self.sondView.SHView_usedView.userInteractionEnabled = YES;
        self.sondView.SHView_balanceView.userInteractionEnabled = YES;
        
        if (self.isToSearchUpdate) {
            // 更新
            if ([model.EListModel count] <= 0) {
                _searchModelAry = nil;
                [self.searchTableView reloadData];
                //_isLoadDataBtn  = YES;
                [self.searchTableView addSubview:[self notDataBtn]];
            }
            else {
                
                [self.notDataBtn removeFromSuperview];
                [self setUpQuickSearch:model.EListModel];
                //刷新数据查看未读信息
                //([EquipmenCellViewModel getEquipmenVM].unreadCount.intValue )
                self.navigationController.tabBarItem.badgeValue = [SearchViewModel sharedSearchViewModel].unreadCount;
                [UIApplication sharedApplication].applicationIconBadgeNumber = [SearchViewModel sharedSearchViewModel].unreadCount.intValue;
            }
            self.clickFinished  = true;
             //isChdoneButClick = NO; //设置回默认值
        }
        else {
            // 加载
            if ([model.EListModel count] == 0) {
                [self.searchTableView.footer endRefreshingWithNoMoreData];
            }
            else {
                [self setUpQuickSearch:model.EListModel];
            }
        }

    } failure:^(NSString *error) {
        [self.searchTableView.header endRefreshing];
        [self.searchTableView.footer endRefreshing];
        self.sondView.SHView_timeView.userInteractionEnabled = YES;
        self.sondView.SHView_usedView.userInteractionEnabled = YES;
        self.sondView.SHView_balanceView.userInteractionEnabled = YES;
    }];
    
}

- (void)setUpQuickSearch:(NSArray *)Ary {
    if (self.isToSearchUpdate) {
        NSMutableArray* mutaAry = [[NSMutableArray alloc] init];
        [mutaAry addObjectsFromArray:Ary];
        _searchModelAry         = mutaAry;
        [self.searchTableView reloadData];
    }
    else {
        NSMutableArray* mutaAry = [[NSMutableArray alloc] init];
        [mutaAry addObjectsFromArray:_searchModelAry];
        [mutaAry addObjectsFromArray:Ary];
        _searchModelAry         = mutaAry;
        [self.searchTableView reloadData];
    }
   
}

#pragma mark - 初始化pop 地区选择
/**  初始化 Nav UI */
- (void)setupMiddleNavigationItem {
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 38, 40)];
    view.backgroundColor = [UIColor clearColor];
    
    // 图片
    UIImageView* image = [[UIImageView alloc] initWithFrame:CGRectMake(3, view.frame.size.height / 2 - 18, 30, 30)];
    [image setImage:[UIImage imageNamed:@"userinfo_navigationbar_search"]];
    [view addSubview:image];
    
    // 搜索输入框
    _searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(image.frame.size.width + 10, 5, SCREEN_WIDTH - 100, 26)];
    _searchTextField.backgroundColor = [UIColor clearColor];
    _searchTextField.textColor = [UIColor whiteColor];
    UIColor* color = RGB(204, 204, 204, 1);
    _searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"search", nil) attributes:@{ NSForegroundColorAttributeName : color }];
    
    _searchTextField.delegate = self;
    [view addSubview:_searchTextField];
    
    // 线条
    UIView* lineView = [[UIView alloc] initWithFrame:CGRectMake(0, view.frame.size.height - 8, view.frame.size.width - 18, 1)];
    lineView.backgroundColor = [UIColor whiteColor];
    [view addSubview:lineView];
    // 加入Item
    self.navigationItem.titleView = view;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"扫二维码Icon" highImageName:@"扫二维码Icon" title:@"" target:self action:@selector(SearchDataAcion:)];
    
    [self UpdataSearchMenuView];
}


/** 初始化 地区选择框 UI */
- (void)UpdataSearchMenuView {
    self.maskView = [self returnMaskView:@selector(hideMyPicker)];
    self.pickerView.width = SCREEN_WIDTH;
    self.ckBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH / 2) - 26, 0, 52, 20)];
    [self.ckBtn setImage:[UIImage imageNamed:@"地区关闭按钮"] forState:UIControlStateNormal];
    [self.ckBtn addTarget:self action:@selector(hideMyPicker) forControlEvents:UIControlEventTouchDown];
}



/** 请求地区数据*/
- (void)requestCityData {
  
    parameterDic = @{@"local":[NSNumber numberWithInt:[self localStr].intValue]};
    [SearchCityViewModel requestWithUrlForSearchIn:self andParam:parameterDic success:^(id model) {
        
        self.pickerView.SRCView_countryAry = [[NSMutableArray alloc] init];
        self.pickerView.SRCView_provinceAry = [[NSMutableArray alloc] init];

        NSLog(@"-------%@",model);
        for (SearchCityModel* city in model) {
            [self.pickerView.SRCView_countryAry addObject:city.name];
            [self.pickerView.SRCView_provinceAry addObject:city.provinces];
        }
        [self.pickerView.cityTableView reloadData];
    } failure:^(NSString *error) {
        
    }];
}

/** 地区选择框隐藏 */
- (void)hideMyPicker {
    areaButClick = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.alpha                = 0;
        self.pickerView.top              = self.view.height;
        self.tabBarController.tabBar.top =  self.view.bottom -_tabBartHeight;
        self.ckBtn.top                     = self.view.bottom;
    }
                     completion:^(BOOL finished) {
                         [self.maskView removeFromSuperview];
                         [self.pickerView removeFromSuperview];
                         [self.ckBtn removeFromSuperview];
                     }];
}

/**  扫描事件 */
- (void)SearchDataAcion:(UINavigationItem*)nav {
    if (TARGET_IPHONE_SIMULATOR) {
        NSLog(@"请使用设备进行测试！");
    }
    else {
        CtrlCodeScan* scan = [[CtrlCodeScan alloc] init];
        scan.delegate = self;
        [self presentViewController:scan animated:YES completion:^{
            
        }];
    }
    
    
}


#pragma mark - TableView Delegate
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    UITableViewCell* cellheight = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cellheight.frame.size.height;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section {
    return _sondView.frame.size.height;
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    UIView* son = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _sondView.frame.size.height)];
    [son addSubview:_sondView];
    return son;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath*)indexPath {
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:indexPath.row]  forKey:RECORD_INDEX_PATH];
    isDetermineClick = YES;
    
    if (isDetermineClick == YES) {
        [self.searchTextField resignFirstResponder];
        
        EListModel* list = _searchModelAry[indexPath.row];
        recordChoiceDevice = list.deviceCode;
        [self subtractUnreadCount:list.unreadCount];
        [list setValue:@0 forKey:@"unreadCount"];
        
        // 数组 替换的下标  ， 替换赋予的内容
        //[_searchModelAry replaceObjectAtIndex:indexPath.row withObject:list];
        // 更新 cell
        NSIndexPath* indexPaths = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        [self.searchTableView reloadRowsAtIndexPaths:@[ indexPaths ] withRowAnimation:UITableViewRowAnimationNone];
        isDetermineClick = NO;
        [SearchViewModel jumpListDetailWithListModel:_searchModelAry[indexPath.row] forViewController:self];
        
    }
}
// 计算偏移量
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (scrollView.contentOffset.y < - 54) {
        [self.sondView isRedDotSort:YES]; //使用 红点排序
    }
}


#pragma mark -  TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger row = _searchModelAry.count;
    return row;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    static NSString* stat = @"EquipmenCell";
    EquipmenCell* cell = (EquipmenCell*)[tableView dequeueReusableCellWithIdentifier:stat];
    if (!cell) {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"EquipmenCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        [tableView registerNib:[UINib nibWithNibName:@"EquipmenCell" bundle:nil] forCellReuseIdentifier:stat];
        cell.delegate = self;
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    EListModel* newlist = _searchModelAry[indexPath.row];
    [cell judgeBtnVlue:newlist.unreadCount isDetermineClick:isDetermineClick];
    [cell setvalueWithList:_searchModelAry[indexPath.row]];
    return cell;
}

// 这里可以指定那一条是否可以编辑
- (BOOL)tableView:(UITableView*)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath {
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath {
    if ([ROLEDODE isEqualToString:@"006"]) {
        return UITableViewCellEditingStyleDelete;
    }
    else {
        return UITableViewCellEditingStyleNone;
    }
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
      if (editingStyle == UITableViewCellEditingStyleDelete) {
                    //数据请求
                    NSDictionary* dic = @{ @"devices" : [_searchModelAry[indexPath.row] deviceCode] };
                    [SearchViewModel requestWithUrlForDeviceRemoveBinding:@"deviceList/deviceRemoveBinding.asp" andParam:dic success:^(RemoveBindingModel *model) {
                        
                        [self requestCityData];
                        // 清nil
                        if (_searchModelAry.count <= 1) {
                            self.navigationController.tabBarItem.badgeValue = nil;
                        }
                        
                        EListModel * lis = _searchModelAry[indexPath.row];
                        NSString* status =  [NSString stringWithFormat:@"%ld", (long)[UIApplication sharedApplication].applicationIconBadgeNumber]; // 获取推送总数
                        int  i = status.intValue - lis.unreadCount;
                        [UIApplication sharedApplication].applicationIconBadgeNumber = i;
                        
                        [_searchModelAry removeObjectAtIndex:indexPath.row]; //删除数据源   _searchModelAry.mutableCopy，如果_searchModelAry,是可变的 再来用mutableCopy 会导致数据无法删除
                        [self.searchTableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic]; //删除自己tavleView 的数据
                        [header beginRefreshing];
                        
                    } failure:^(NSString *error) {
                        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
                    }];
            }
}



//FIXME: 这里需要重新考虑
/* 输入框代理 */
#pragma mark - TextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField {
    if (areaButClick) {
        [self hideMyPicker];
    }
    
    
    [keyboardvView removeFromSuperview];
    keyboardvView = [self returnMaskView:@selector(clickview:)];
    [self.view addSubview:keyboardvView];
    keyboardvView.tag = 500;
    [self.view bringSubviewToFront:keyboardvView];

    [UIView animateWithDuration:1.0 animations:^{
        keyboardvView.alpha = 0.3;
    }];

    keyboardvView.userInteractionEnabled = YES;
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField {
    [textField resignFirstResponder];
    UIView *view = [self.view viewWithTag:500];
    [UIView animateWithDuration:1.0 animations:^{
        view.alpha = 0;
    }];
    return YES;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
    [textField addTarget:self action:@selector(textfielddidChanged:) forControlEvents:UIControlEventEditingChanged]; //监控状态
    return YES;
}
- (void)textfielddidChanged:(UITextField*)textfield {
    UITextRange* selectedRange = self.searchTextField.markedTextRange;
    if (selectedRange == nil || selectedRange.empty) {
        [header beginRefreshing];
    }
    else {
        // continue;
    }
}
- (void)resignkeyboard { [self.searchTextField endEditing:YES];
                    //[self.searchTextField resignFirstResponder];
}

// TODO:这里需要优化 －－点击view收键盘
-(void)clickview:(UITapGestureRecognizer *)tap
{
    UIView *view = [self.view viewWithTag:500];
    [UIView animateWithDuration:1.0 animations:^{
        view.alpha = 0;
    }];
    
    [self resignkeyboard];
}




/** 二维码设备代理 */
#pragma mark - SystemInfoController Delegate
- (void)dismissViewControllerWithDeviceVlue:(NSString *)Str {
    [self requestCityData];
    NSMutableDictionary* mutDic = [[NSMutableDictionary alloc] init];
    [mutDic setObject:@"" forKey:@"c_area"];
    [mutDic setObject:@"2015-10-06 10:42:21" forKey:@"latestUse"];
    [mutDic setObject:@"" forKey:@"ic_money"];
    [mutDic setObject:Str forKey:@"deviceCode"];
    [mutDic setObject:@"" forKey:@"total_flow"];
    [mutDic setObject:@"" forKey:@"state"];
    EListModel* equModel = [EListModel mj_objectWithKeyValues:mutDic];
    
    NSLog(@"%@", equModel);
    NSArray* sideBarAry = @[ equModel ];
    
    _searchModelAry = [_searchModelAry arrayByAddingObject:sideBarAry[0]].mutableCopy;
    if (_searchModelAry == nil) {
        _searchModelAry = [[NSMutableArray alloc] initWithObjects:sideBarAry[0], nil];
    }
    NSIndexPath* inPath = [NSIndexPath indexPathForRow:[_searchModelAry count] - 1 inSection:0]; //修改后是： 0 - 原来是 ：self.searchTableView.indexPathForSelectedRow.section
    NSLog(@"打印： %@--->%lu-+-->%ld", inPath, (unsigned long)inPath.length, (long)inPath.section);
    [self.searchTableView insertRowsAtIndexPaths:@[ inPath ] withRowAnimation:UITableViewRowAnimationLeft]; //插入的位置数组，后面参数是动画
    [header beginRefreshing];
}

/* 扫描结果代理 */
#pragma  mark - CtrlCodeScan Delegate
- (void)didCodeScanOk:(id)info {
    NSLog(@"获取到二维码内容：--->%@", info);
    // 判断是否包含以下内容
    if ([info rangeOfString:@"https://itunes.apple.com/us/app/oilklenze/id1007167022?l=zh&ls=1&mt=8&code="].location != NSNotFound) {
        UIStoryboard* story = [UIStoryboard storyboardWithName:@"Main" bundle:NULL];
        [[NSUserDefaults standardUserDefaults] setObject:info forKey:@"scanInfo"];
        NSString* infoStr= [NSString stringWithFormat:@"%@", info];
        
        NSDictionary* parameters = @{ @"deviceQRCode" : [infoStr substringFromIndex:(infoStr.length - 22)] };
        
        NSLog(@"%@",parameters);
       
        [EquipmenDetailsViewModel requestWithUrlForDeviceDetails:self andParam:parameters success:^(DeviceDetailsModel *model) {
            if ( model != nil) {
                SystemInfoController *info  = [story instantiateViewControllerWithIdentifier:@"SystemInfo"];
                info.delegate = self;
                info.detailsAry = [NSMutableArray arrayWithObjects:model, nil];
                [self presentViewController:info animated:YES completion:nil];
            }

        } failure:^(NSString *error) {
            
        }];
        }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/oilklenze/id1007167022?l=zh&ls=1&mt=8&code="]];
    }
}

/* 排序View代理*/
#pragma mark - SearchHeadView Delegate
- (void)searchHeadViewWithRefreshData {
    [header beginRefreshing];
}
- (void)hairPromotionControlMethod {
    areaButClick = YES;
    [self resignkeyboard];
    [self requestCityData];
    
    // 动画
    self.maskView.alpha                = 0.1;
    self.pickerView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, self.pickerView.height);
    self.ckBtn.top                     = self.view.frame.size.height;
    // 隐藏tabBar
    
    [self.view addSubview:self.maskView];
    [self.view addSubview:self.pickerView];
    [self.view addSubview:self.ckBtn];
   _tabBartHeight =  self.tabBarController.tabBar.height;
   // self.tabBarController.tabBar.height =f1;
    [UIView animateWithDuration:0.5 animations:^{
        self.tabBarController.tabBar.top = self.view.bottom;
    }];
    
}

/* 地区选择View代理*/
#pragma  mark - SearchRegionChoice Delegate
- (void)pickViewSetHigh:(float)high {
    [UIView animateWithDuration:0.3 animations:^{
        
        self.maskView.alpha                = 0.1;
        self.pickerView.frame = CGRectMake(0, self.view.frame.size.height-high, self.view.frame.size.width, high);
        self.ckBtn.bottom                  = self.view.height - high;
    }];
}
- (void)pickerViewWillHide:(SearchRegionChoiceView *)view {
    isChdoneButClick = view.isOpenAreaValue;
    [self hideMyPicker];
}
- (void)refreshSearchData:(SearchRegionChoiceView *)view {
    [self searchHeadViewWithRefreshData];
    // 控制 ALL AREAS ,根据选中的地区搜索值显示
    if ([view.SRCView_searchValueStr isEqualToString:@""]) {
        [self.sondView.SHView_regionSelectionBtn setTitle:NSLocalizedString(@"ALL AREAS", nil) forState:UIControlStateNormal];
    }else {
        [self.sondView.SHView_regionSelectionBtn setTitle:view.SRCView_searchValueStr forState:UIControlStateNormal];
    }
    
}


#pragma mark - Segues
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"jumpJournalList"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:recordChoiceDevice  forKey:@"journalDeviceCode"];
    }
}



#pragma mark - set/ get
- (UIView *)returnMaskView:(SEL)method {
    UIView *mask = [[UIView alloc] initWithFrame:SCREEN_FRAME];
    mask.backgroundColor = [UIColor clearColor];
    mask.alpha = 0;
    mask.tag = 501;
    [mask addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:method]]; // 隐藏方法
    return mask;
}

- (UIButton *)notDataBtn {
    if (!_notDataBtn) {
        _notDataBtn = [[UtilToolsClss getUtilTools] noDataBtn];
    }
    return _notDataBtn;
}

- (NSString *)localStr {
    if (!_localStr) {
        _localStr = [NSString stringWithFormat:@"%d",[UtilToolsClss judgeLocalLanguage]];
    }
    return _localStr;
}

- (AppDelegate*) appDelegate {
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

@end
